<? defined('SYSPATH') or die('No direct script access');

class Main_Controller extends Base_Controller {

    public $template = 'templates/base';

    public function index() {

        // get month and year from $_GET, default value is current month/year
        $month = $this->input->get('month', date('m'));
        $year = $this->input->get('year', date('Y'));

        // update calendar for input month and year
        $this->calendar = new Calendar($month, $year);

        // populate calendar with all events for the current month
        $this->add_events($month, $year);

        // add event for today
        $this->calendar->standard('today');

        // set template content
        $this->template->title = 'jynxit';
        $this->template->content = $this->calendar->render('calendar/calendar');
        $this->template->sidebar = new View('sidebar/calendar-tabs');
    }

    /*
     * Attaches all events for the given month and year to the calendar
     * @param integer month (1-12)
     * @param integer year (4 digits)
     * @return Calendar updated calendar
     */
    public function add_events($month, $year) {
        
        // event model
        $event_model = new Event_Model;

        // first day of month as timestamp
        $start = mktime(0, 0, 0, $month, 1, $year);

        // last day of month as timestamp
        $end = mktime(23, 59, 59, $month, date('t', $month), $year);

        // get all events for given month/year
        // TODO: Update for user_id from session.
        $event_list = $event_model->get_event_list(1, $start, $end);

        //attach events to calendar
        foreach ($event_list as $event) {

            // convert dates from MySQL to Unix
            $start_time = $event_model->mysql_to_php_date($event->starttime);

            $this->calendar->attach($this->calendar->event()->condition('year', date('Y', $start_time))
                                                            ->condition('month', date('m', $start_time))
                                                            ->condition('day', date('j', $start_time))
                                                            ->output(html::anchor('event/event_detail/'.$event->id, $event->name)));
            
        }


    }

    public function event_search() {
        $event_model = new Event_Model;
        $input = $this->input->post('search');
        $results = $event_model->search_fulltext($input);

        $html = '<table>';

        foreach($results as $result) {
            $html .= '<tr><td>'.html::anchor('event/event_detail/'.$result->id, $result->name).'</td></tr>';
        }

        $html .= '</table>';
        
        if (request::is_ajax()) {
            $this->auto_render = false;
            echo json_encode($html);
        }
    }
}

?>
